
init();

function init() {
    loads();
}

function loads(){
    var load = document.getElementsByClassName('load')[0],
        start = document.getElementsByClassName('start')[0],
        off = true;

        addEvent(start, 'click', startGame);
        addEvent(document, 'keydown', function(ev){
            var e = ev || window.event,
                code = e.keyCode;
                

            if(code === 32 && off){
                startGame();
            }
        });

        function startGame(){
            load.style.display = 'none';
            SnakeGame();
            off = false;
        }
}

var SnakeGame = (function () {
    var wrap = document.getElementsByClassName('wrap')[0],
        grade = document.getElementsByClassName('gradeNum')[0],
        oWdt = getStyle(wrap, 'width'),
        oHit = getStyle(wrap, 'height'),
        timer = null,
        count = 0,
        item;

    Snake = function () {
        this.bodyArr = [{
                    x: 0,
                    y: 0
                },
                {
                    x: 0,
                    y: 20
                }
            ],
            // 蛇的初始移动方向
            this.dir = 'DOWN';
    }


    Snake.prototype = {
        init: function () { // 将处理函数统一执行
            this.run(); // 蛇的移动
            this.bindEvent(); // 设置监听事件
            this.drawSnake(); // 绘制蛇的位置
            this.createFood(); // 创建食物
        },
        bindEvent: function () {
            var _self = this;
            // 按键控制
            addEvent(document, 'keydown', function () {
                _self.changeDir();
            });
        },
        drawSnake: function () { // 绘制蛇
            var temp = document.createDocumentFragment(),
                arr = this.bodyArr,
                len = arr.length;

            for (var i = 0; i < len; i++) {
                item = arr[i];

                var round = document.createElement('i');
                // 如果是最后一节的话 就给它加上一个头部的类名 是第一节就加上脚部的类名
                round.className = i === len - 1 ? 'round head' : 'round';
                round.style.left = item.x + 'px';
                round.style.top = item.y + 'px';
                temp.appendChild(round)
            }
            wrap.appendChild(temp);
        },
        reDraw: function () { // 清除上一次的蛇
            var bodys = document.getElementsByClassName('round');
            while (bodys.length > 0) { // 只要蛇还没有完全在页面小时就一直清除
                bodys[0].remove();
            }
        },
        move: function () { //蛇位置的修改
            var arr = this.bodyArr,
                len = arr.length,
                head = arr[len - 1];
            for (var i = 0; i < len; i++) {
                // 循环到的 i 如果是头部的话
                if (i === len - 1) {
                    // 当按下方向键以后 蛇会做出的行为动作
                    switch (this.dir) {
                        case 'LEFT':
                                head.x -= 20;                            
                            break;
                        case 'RIGHT':
                                head.x += 20;                            
                            break;
                        case 'UP':
                                head.y -= 20;                            
                            break;
                        case 'DOWN':
                                head.y += 20;                            
                            break;
                        default:
                            break;
                    }

                    // 判定是否出界
                    if (head.x >= oWdt) {
                        head.x = 0;
                    } else if (head.x < 0) {
                        head.x = oWdt;
                    }
                    if (head.y >= oHit) {
                        head.y = 0;
                    } else if (head.y < 0) {
                        head.y = oHit;
                    }

                } else {
                    arr[i].x = arr[i + 1].x;
                    arr[i].y = arr[i + 1].y;
                }
            }
            this.feedFood(); // 吃到食物以后
            this.reDraw(); // 清除上一次的蛇
            this.drawSnake(); //绘制蛇
            this.youDie();
        },
        run: function () { // 蛇自动移动
            var _self = this;
            timer = setInterval(function () {
                _self.move();
            }, 120);
        },
        changeDir: function (ev) { // 检测按下的键
            var e = ev || window.event,
                code = e.keyCode;
            this.setDir(code);
        },
        setDir: function (code) { // 设置按键状态
            switch (code) {
                case 37:
                case 65:
                    if (this.dir !== 'RIGHT' && this.dir !== 'LEFT') {
                            this.dir = 'LEFT';
                    }
                    break;
                case 39:
                case 68:
                    if (this.dir !== 'RIGHT' && this.dir !== 'LEFT') {
                            this.dir = 'RIGHT';
                    }
                    break;
                case 38:
                case 87:
                    if (this.dir !== 'UP' && this.dir !== 'DOWN') {
                            this.dir = 'UP';
                    }
                    break;
                case 40:
                case 83:
                    if (this.dir !== 'UP' && this.dir !== 'DOWN') {
                            this.dir = 'DOWN';
                    }
                    break;
                default:
                    break;
            }
            this.feedFood();
        },
        createFood: function () { // 生成食物
            var food = document.createElement('i'),
                numx = this.setRandomPos(oWdt),
                numy = this.setRandomPos(oHit),
                arr = this.bodyArr,
                len = arr.length;

            food.className = 'food';

            for (var i = 0; i < len; i++) {
                item = arr[i];

                // 如果坐标重叠了则加上20 防止生成在体内
                if (numx === item.x && numy === item.y) {
                    // 如果生成到了地图外面
                    if (numx >= oWdt - 20) {
                        numx = oWdt - 20;
                    } else if (numy >= oHit - 20) {
                        numy = oHit - 20;
                    }

                    if (numx <= 0) {
                        numx = 0;
                    } else if (numy <= 0) {
                        numy = 0;
                    }
                    numx += 20;
                    numy += 20;
                } else {
                    food.style.left = numx + 'px';
                    food.style.top = numy + 'px';
                }
            }

            wrap.appendChild(food);
        },
        feedFood: function () { // 判断蛇是否吃到了食物
            var food = document.getElementsByClassName('food')[0],
                head = document.getElementsByClassName('head')[0],
                // 获取头部坐标
                headl = getStyle(head, 'left'),
                headt = getStyle(head, 'top'),
                // 获取食物坐标
                foodl = getStyle(food, 'left'),
                foodt = getStyle(food, 'top'),
                arr = this.bodyArr,
                len = arr.length;

            if (headl == foodl && headt == foodt) {
                food.remove();
                arr.push({
                    x: arr[len - 1].x,
                    y: arr[len - 1].y
                });
                this.createFood();
                count++
                grade.innerHTML = count;
            }
        },
        youDie: function () { // 判定游戏结束
            var arr = this.bodyArr,
                len = arr.length,
                headx = arr[len - 1].x,
                heady = arr[len - 1].y;

            for (var i = 0; i < len - 2; i++) {
                item = arr[i];
                if (item.x == headx && item.y == heady) {
                    t = setTimeout(function () {
                        alert("游戏结束");
                        history.go(0);
                    }, 30)
                }
            }
        },
        gameOver: function () { // 游戏结束

            alert('游戏结束!');
        },
        resetGame: function () { // 重新开始
            clearInterval(timer);
            this.run();
            new Snake().init();
        },
        setRandomPos: function (wOrH) { // 计算食物的坐标值
            return Math.floor(Math.random() * wOrH / 20) * 20;
        }
    }

    return new Snake().init();
});